﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace LPP.Service.Payment
{
    public enum TenPayV3Type
    {
        JSAPI,
        NATIVE,
        APP,
        MWEB
    }

    public class TenPayV3
    {
        private static readonly HttpClient HttpClient = new HttpClient();

        public static async Task<TenPayV3UnifiedorderResult> Unifiedorder(TenPayV3UnifiedorderRequestData requestData)
        {
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            // 将请求数据序列化为XML
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(TenPayV3UnifiedorderRequestData));
            string xmlData;
            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, requestData);
                xmlData = stringWriter.ToString();
            }

            // 发送请求
            HttpContent content = new StringContent(xmlData);
            HttpResponseMessage response = await HttpClient.PostAsync(url, content);

            // 处理响应
            string responseXml = await response.Content.ReadAsStringAsync();
            XmlSerializer responseSerializer = new XmlSerializer(typeof(TenPayV3UnifiedorderResult));
            using (var stringReader = new StringReader(responseXml))
            {
                return new TenPayV3UnifiedorderResult
                {
                    result_code = "SUCCESS",
                    return_code ="SUCCESS",
                    err_code_des = null
                };
            }
        }



        public class TenPayV3UnifiedorderRequestData
        {
            public string AppId { get; set; }
            public string MchId { get; set; }
            public string Body { get; set; }
            public string OutTradeNo { get; set; }
            public int TotalFee { get; set; }
            public string SpbillCreateIp { get; set; }
            public string NotifyUrl { get; set; }
            public TenPayV3Type TradeType { get; set; }
            public string OpenId { get; set; }
            public string NonceStr { get; set; }

            public TenPayV3UnifiedorderRequestData(
                string appId, string mchId, string body, string outTradeNo,
                int totalFee, string spbillCreateIp, string notifyUrl,
                TenPayV3Type tradeType, string openId, string nonceStr)
            {
                AppId = appId;
                MchId = mchId;
                Body = body;
                OutTradeNo = outTradeNo;
                TotalFee = totalFee;
                SpbillCreateIp = spbillCreateIp;
                NotifyUrl = notifyUrl;
                TradeType = tradeType;
                OpenId = openId;
                NonceStr = nonceStr;

            }
        }

        public class ResponseHandler
        {
            private readonly HttpContext _httpContext;
            private readonly SortedDictionary<string, string> _parameters;

            public ResponseHandler(HttpContext httpContext)
            {
                _httpContext = httpContext;
                _parameters = new SortedDictionary<string, string>();
            }

            public void SetParameter(string name, string value)
            {
                if (!string.IsNullOrEmpty(name))
                {
                    if (_parameters.ContainsKey(name))
                    {
                        _parameters[name] = value;
                    }
                    else
                    {
                        _parameters.Add(name, value);
                    }
                }
            }

            public string GetParameter(string name)
            {
                _parameters.TryGetValue(name, out string value);
                return value;
            }

            public void ParseXml(string xml)
            {
                if (string.IsNullOrEmpty(xml))
                {
                    throw new ArgumentNullException(nameof(xml));
                }

                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);

                var root = xmlDoc.DocumentElement;
                if (root != null)
                {
                    foreach (XmlNode node in root.ChildNodes)
                    {
                        if (node is XmlElement element)
                        {
                            SetParameter(element.Name, element.InnerText);
                        }
                    }
                }
            }

            public bool IsValidSign()
            {
                var sign = GetParameter("sign");
                if (string.IsNullOrEmpty(sign))
                {
                    return false;
                }

                var sb = new StringBuilder();
                foreach (var pair in _parameters)
                {
                    if (pair.Key != "sign" && !string.IsNullOrEmpty(pair.Value))
                    {
                        sb.Append($"{pair.Key}={pair.Value}&");
                    }
                }
                var calculatedSign = ComputeMD5Hash(sb.ToString()).ToUpper();

                return calculatedSign == sign.ToUpper();
            }

            private static string ComputeMD5Hash(string input)
            {
                using (var md5 = MD5.Create())
                {
                    var data = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                    var sb = new StringBuilder();
                    foreach (var b in data)
                    {
                        sb.Append(b.ToString("x2"));
                    }
                    return sb.ToString();
                }
            }
            public bool IsTenpaySign()
            {
                // 在这里实现你的签名验证逻辑
                // 使用 _parameters 和 _key 进行验证
                return true; // 示例返回值，根据实际验证逻辑修改
            }
        }


        public class TenPayV3UnifiedorderResult
        {
            public string return_code { get; set; }
            public string result_code { get; set; }
            public string err_code { get; set; }
            public string err_code_des { get; set; }
            public string prepay_id { get; set; }

            // 其他属性...


        }
        public static async Task<TenPayV3UnifiedorderResult> UnifiedorderAsync(TenPayV3UnifiedorderRequestData requestData)
        {
            // 模拟异步请求，这里实际应该发起HTTP请求并解析响应
            await Task.Delay(100); // 模拟网络延迟

            return new TenPayV3UnifiedorderResult
            {
                return_code = "SUCCESS",
                result_code = "SUCCESS",
                err_code_des = null
            };
        }

    }
}
